package com.hup.utils.swing.frame;

import com.hup.utils.commons.hardware.ScreenUtil;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;

/**
 * @author hugan
 * @date 2019/10/9
 */
public class InfoWindow extends JWindow {

    private JLabel labInfo;

    public InfoWindow() {
        setAlwaysOnTop(true);
        labInfo = new JLabel();
        labInfo.setBorder(new LineBorder(Color.gray, 1));
        labInfo.setBackground(new Color(255, 255, 225));
        labInfo.setOpaque(true);
        add(labInfo);
    }

    public void setInfo(String info) {
        labInfo.setText(info);
    }

    public void show(Component target, WinLoc type) {
        pack();

        Point location = WinLoc.getLoc(type, target, this);
        setLocation(location);

        setVisible(true);
    }

    public void show(String info, Component target, WinLoc type) {
        setInfo(info);
        show(target, type);
    }

    /**
     * 窗口展示的位置
     */
    public enum WinLoc {
        /**
         * 在目标的左下方
         */
        BOTTOM,
        /**
         * 在目标的左侧
         */
        LEFT;

        private static Point getLoc(WinLoc type, Component target, Component win) {
            Point res;
            if (type == BOTTOM) {
                res = bottom(target, win);
            } else if (type == LEFT) {
                res = left(target, win);
            } else {
                throw new IllegalArgumentException("type异常");
            }
            return res;
        }

        private static Point bottom(Component target, Component win) {
            Point tarLoc = target.getLocationOnScreen();
            Point res = new Point(tarLoc.x, tarLoc.y + target.getHeight());
            //如果win底部越界,则底部定在屏幕边缘
            Dimension scrSize = ScreenUtil.getScreenSize();
            int scrHeight = scrSize.height;
            if (res.y + win.getHeight() > scrHeight) {
                res.y = Math.max(0, scrHeight - win.getHeight());

                res.x = tarLoc.x - win.getWidth();
                if (res.x < 0) {
                    //如果win左边越界,则在右边展示
                    res.x = (int) (tarLoc.getX() + target.getWidth());
                }
            }
            if (res.x + win.getWidth() > scrSize.width) {
                res.x = Math.max(0, scrSize.width - win.getWidth());
            }
            return res;
        }

        private static Point left(Component target, Component win) {
            Point tarLoc = target.getLocationOnScreen();
            Point res = new Point(tarLoc.x - win.getWidth(), tarLoc.y);
            if (res.x < 0) {
                //如果win左边越界,则在右边展示
                res.x = (int) (tarLoc.getX() + target.getWidth());
            }
            //如果win底部越界,则底部定在屏幕边缘
            int scrHeight = ScreenUtil.getScreenSize().height;
            if (res.y + win.getHeight() > scrHeight) {
                res.y = Math.max(0, scrHeight - win.getHeight());
            }
            return res;
        }
    }

}
